package com.laikan.reader.bookfriend.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import thirdparty.cn.sharesdk.onekeyshare.OnekeyShare;

public class EventWebViewActivity extends BasicActivity implements OnClickListener {

    private ImageView back_tv;
    private String url;
    private TextView title_tv;
    private RelativeLayout back_layout;
    private int width,height;
    private Bitmap back_tv_bitmap,bitmap;
    /**
     * 标题栏
     */
//    private CommonTitleLayout ctl_title;
    private WebView webview;
    private LoadingDialog loadingDialog;
    private String title;

	/*
     * android2.2.3的bug在js中调这个方法时出现: JNI WARNING: jarray 0x4054d218 points to
	 * non-array object (Lja
	 */

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_layout:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_webview);
        loadingDialog = new LoadingDialog(this);
        if (null != loadingDialog && !loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        ViewTreeObserver vto1 = back_tv.getViewTreeObserver();
        vto1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                back_tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                width = back_tv.getWidth();
                height = back_tv.getHeight();
                back_tv_bitmap =  PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext,R.drawable.lk_back_small), Color.parseColor("#66ccdd"));
                bitmap =PublicUtil.resizeBitmap(back_tv_bitmap,width,height);
                back_tv.setImageBitmap(bitmap);
            }
        });
        url = getIntent().getStringExtra("mHtmlUrl");
        title = getIntent().getStringExtra("title");
        title_tv.setText(title);
//      ctl_title.setTitle(title);
        webview = (WebView)findViewById(R.id.webview);
        // back_tv.setOnClickListener(this);
        String weburl = "http://www.laikan.com/android/2/festival/egg_frenzy2015_08";
        webview.setWebViewClient(new MyWebViewClient());
        webview.setWebChromeClient(new MyWebChromeClient());

        WebSettings websettings = webview.getSettings();
        websettings.setJavaScriptEnabled(true);// 可以使用javascript------!
        webview.addJavascriptInterface(new CallJavaInterface(), "demo");// 通过调这个注册
        webview.postUrl(url, ("sd=" + SPUtil.getString("token", "")).getBytes());
         back_tv =(ImageView)findViewById(R.id.iv_back);
         back_layout = (RelativeLayout)findViewById(R.id.back_layout);
         title_tv =(TextView)findViewById(R.id.tv_title);
//        ctl_title = (CommonTitleLayout)findViewById(ctl_title);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);

    }

    public void showShare(String title, String desc, String img) {
        String urlmobile = "http://m.laikan.com/huodong/2015Dec";
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        oks.setTitleUrl(urlmobile);
        String str = "";
        if (desc.length() > 119) {
            str = desc.substring(0, 118) + "...";
        }else {
            str = desc;
        }
        oks.setText(str);
        oks.setImageUrl(img);//
        oks.setUrl(urlmobile);
        oks.setComment(img);
        oks.setSite(getString(R.string.app_name));
        oks.setSiteUrl(urlmobile);
        oks.show(this);
    }

    private class CallJavaInterface {

        public String calljava(String name) {
            return name;
        }
    }

    private class MyWebChromeClient extends WebChromeClient {

        // @Override
        // public boolean onJsAlert(WebView view, String mHtmlUrl, String message,
        // JsResult result) {
        // AlertDialog ad = new AlertDialog.Builder(EventWebViewActivity.this)
        // .setTitle("警告对话框").setMessage(message)
        // .setPositiveButton("确定", null).create();
        // // ad.show();
        // result.confirm();
        // return true;
        // // return super.onJsAlert(view, mHtmlUrl, message, result);
        // }
        //
        // @Override
        // public boolean onJsConfirm(WebView view, String mHtmlUrl, String message,
        // final JsResult result) {
        // AlertDialog ad = new AlertDialog.Builder(EventWebViewActivity.this)
        // .setTitle("确认对话框")
        // .setMessage(message)
        // .setPositiveButton("确定",
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // result.confirm();
        // }
        // })
        // .setNegativeButton("取消",
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // result.cancel();
        // }
        // }).create();
        // ad.show();
        // return true;
        // // return super.onJsConfirm(view, mHtmlUrl, message, result);
        // }
        //
        // @Override
        // public boolean onJsPrompt(WebView view, String mHtmlUrl, String message,
        // String defaultValue, final JsPromptResult result) {
        // EditText et = new EditText(EventWebViewActivity.this);
        // et.setText(defaultValue);
        //
        // AlertDialog ad = new AlertDialog.Builder(EventWebViewActivity.this)
        // .setTitle("输入对话框")
        // .setMessage(message)
        // .setView(et)
        // .setPositiveButton("确定",
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // result.confirm();// 返结果用带参的
        // }
        // })
        // .setNegativeButton("取消",
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog,
        // int which) {
        // result.cancel();
        // }
        // }).create();
        // ad.show();
        // return true;
        // // return super.onJsPrompt(view, mHtmlUrl, message, defaultValue,
        // // result);
        // }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (null != loadingDialog && loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
            }
            super.onProgressChanged(view, newProgress);
        }

    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onLoadResource(WebView view, String url) {

            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String weburl) {

            if (weburl.contains("share")) {

                Uri uri = Uri.parse(weburl);
                String title = uri.getQueryParameter("title");
                String desc = uri.getQueryParameter("desc");
                String img = uri.getQueryParameter("img");
                showShare(title, desc, img);
                return true;
            }else if (weburl.contains("pay")) {

                startActivity(new Intent().setClass(mContext, RechargePage.class));
                return true;
            }

            // String regEx =
            // "motieapp://laikan/openwith/share(.*?)title=(.*?)&desc=(.*?)&img=(.*)";
            // Pattern p = Pattern.compile(regEx);
            // Matcher m = p.matcher(mHtmlUrl);
            // if(m.find()){
            // String sequence1 = URLDecoder.decode(m.group(2));
            // String sequence2 = URLDecoder.decode(m.group(3));
            // String sequence3 = m.group(4);
            // System.out.println(sequence1);
            // System.out.println(sequence2);
            // System.out.println(sequence3);
            //
            // }
            view.postUrl(url, ("sd=" + SPUtil.getString("token", "")).getBytes());
            return true;
        }

    }
}